package com.example.demo04plc.plc.common;

import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Data
@Accessors(chain = true)
public class PlcConnectionConfig {
    private static final Pattern pattern = Pattern.compile("^([\\w-]+)://(.*):(\\d+)\\??(.*)$");

    private String transport;
    private String ipAddress;
    private int port;
    private Map<String, String> options;

    public static PlcConnectionConfig parse(String connectionStr) {
        PlcConnectionConfig plcConnectionConfig = new PlcConnectionConfig();
        Matcher matcher = pattern.matcher(connectionStr);
        if (matcher.matches()) {
            plcConnectionConfig.setTransport(matcher.group(1))
                    .setIpAddress(matcher.group(2))
                    .setPort(Integer.parseInt(matcher.group(3)))
                    .setOptions(getOptions(matcher.group(4)));
        }
        return plcConnectionConfig;
    }
    private static Map<String, String> getOptions(String options) {
        if (!StringUtils.hasLength(options)) return new HashMap<>();
        return Arrays.stream(options.split("&"))
                .map(pair -> pair.split("="))
                .filter(keyValue -> keyValue.length == 2)
                .collect(Collectors.toMap(keyValue -> keyValue[0], keyValue -> keyValue[1]));
    }
}
